/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.purpose.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Splitter;
import com.google.gson.Gson;
import com.koron.audit.approval.AfterApprovalService;
import com.koron.audit.domain.Audit;
import com.koron.audit.management.FlowManagement;
import com.koron.common.bean.StaffBean;
import com.koron.common.dfs.FastDFSClientWrapper;
import com.koron.common.domain.DataBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.common.web.Util;
import com.koron.hazardsource.util.Immutable;
import com.koron.purpose.bean.ContractQueryBean;
import com.koron.purpose.bean.PurposeContractBean;
import com.koron.purpose.domain.PurposeContract;
import com.koron.purpose.domain.PurposeContractPersons;
import com.koron.purpose.domain.PurposeItem;
import com.koron.purpose.domain.PurposeObject;
import com.koron.purpose.mapper.PurposeContractMapper;
import com.koron.purpose.mapper.PurposeItemMapper;
import com.koron.purpose.mapper.PurposeObjectMapper;
import com.koron.purpose.service.api.PurposeContractService;
import com.koron.system.utils.BusinessCode;
import com.koron.workflow.service.api.WorkflowService;
import com.koron.workflow.service.impl.WorkflowServiceImpl;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;

import java.util.*;

@Service
public class PurposeContractServiceImpl implements PurposeContractService, AfterApprovalService, InitializingBean {

    private final static Logger logger= LoggerFactory.getLogger(PurposeContractServiceImpl.class);
    // 责任书制定流程 1-集团、2-片区、3-公司、4-部门、5-厂站、6-班组
    @Value("${flow_purpose_contract_jt}")
    private String templateKeyJT;
    // 责任书制定流程 1-集团、2-片区、3-公司、4-部门、5-厂站、6-班组
    @Value("${flow_purpose_contract_pq}")
    private String templateKeyPQ;
    // 责任书制定流程 1-集团、2-片区、3-公司、4-部门、5-厂站、6-班组
    @Value("${flow_purpose_contract_gs}")
    private String templateKeyGS;
    // 责任书制定流程 1-集团、2-片区、3-公司、4-部门、5-厂站、6-班组
    @Value("${flow_purpose_contract_bm}")
    private String templateKeyBM;
    // 责任书制定流程 1-集团、2-片区、3-公司、4-部门、5-厂站、6-班组
    @Value("${flow_purpose_contract_cz}")
    private String templateKeyCZ;
    // 责任书制定流程 1-集团、2-片区、3-公司、4-部门、5-厂站、6-班组
    @Value("${flow_purpose_contract_bz}")
    private String templateKeyBZ;

    @Value("${flow_purpose_contract}")
    private String signTemplateKey;

    @Value("${flow_contract_formulate}")
    private String formulateTemplateKey;

    @Autowired
    private FlowManagement flowManagement;

    @Autowired
    private FastDFSClientWrapper clientWrapper;

    // 状态: 未签订
    private Integer STATE_0 = 0;
    // 状态: 已签订
    private Integer STATE_1 = 1;
    // 状态: 驳回
    private Integer STATE_2 = 2;
    // 流程状态：0草稿
    private Integer FSTATUSFLAG_0 = 0;
    // 流程状态：1审批中
    private Integer FSTATUSFLAG_1 = 1;
    // 流程状态：2审批通过
    private Integer FSTATUSFLAG_2 = 2;
    // 责任书类型：2档案
    private Integer BILLTYPE_1 = 1;
    // 责任书类型：2档案
    private Integer BILLTYPE_2 = 2;

    @Autowired
    private WorkflowService flowService;

/*	@Autowired
	private DocConverterUtils docConverterUtils;*/

    @SuppressWarnings({"unchecked", "rawtypes"})
    @Override
    public void afterPropertiesSet() throws Exception {
        Map map = flowManagement.getHandlers();
        map.put(this.getClass().getName(), new PurposeContractServiceImpl());
    }


    @SuppressWarnings({"rawtypes", "deprecation"})
    @Override
    public MessageBean<?> insert(PurposeContractBean bean, StaffBean user, String title, String note) {
        MessageBean<PurposeContractBean> msg = MessageBean.create(0, "SUCCESS", PurposeContractBean.class);
        // 检查签订人员是否为空
        if (bean.getPersonList() == null || bean.getPersonList().size() == 0) {
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription("签订人员不能为空");
            return msg;
        }
        SessionFactory factory = new SessionFactory();
        List<String> pathList = new ArrayList<>();
        try {
            Map checkMap = addCheck(bean);
            int code = (int) checkMap.get("code");
            String description = (String) checkMap.get("description");
            if (code != 0) {
                msg.setCode(code);
                msg.setDescription(description);
                factory.close(false);
                return msg;
            }
            PurposeContractMapper contractMapper = factory.getMapper(PurposeContractMapper.class);
            PurposeItemMapper itemMapper = factory.getMapper(PurposeItemMapper.class);

            String userCode = user.getCode();
            String userName = user.getName();
            Date date = new Date();
            bean.setAddUser(userCode);
            bean.setAddUserName(userName);
            bean.setAddTime(date);
            bean.setUpdateUser(userCode);
            bean.setUpdateUserName(userName);
            bean.setUpdateTime(date);
            bean.setState(STATE_0);
            bean.setFstatusflag(FSTATUSFLAG_0);
            bean.setBillType(BILLTYPE_1);

            bean.setId(DefaultIdGenerator.getInstance().generateLongId());
			/*List<PurposeObject> objectList = bean.getObjectList();
			for (PurposeObject object : objectList) {
				object.setId(DefaultIdGenerator.getInstance().generateLongId());
				object.setPurposeContractId(bean.getId());
			}*/
            List<PurposeItem> itemList = bean.getItemList();
            for (PurposeItem item : itemList) {
                if (StringUtils.isEmpty(item.getItemId())) {
                    msg.setCode(BusinessCode.EXCEPTION.getCode());
                    msg.setDescription("指标信息不完整");
                    factory.close(false);
                    return msg;
                }
                if (StringUtils.isEmpty(item.getItemName())) {
                    msg.setCode(BusinessCode.EXCEPTION.getCode());
                    msg.setDescription("指标名称不能为空");
                    factory.close(false);
                    return msg;
                }
                if (StringUtils.isEmpty(item.getItemValue())) {
                    msg.setCode(BusinessCode.EXCEPTION.getCode());
                    msg.setDescription("指标值不能为空");
                    factory.close(false);
                    return msg;
                }
                item.setAddUser(userCode);
                item.setAddUserName(userName);
                item.setAddTime(date);
                item.setUpdateUser(userCode);
                item.setUpdateUserName(userName);
                item.setUpdateTime(date);
                item.setId(DefaultIdGenerator.getInstance().generateLongId());
                item.setPurposeContractId(bean.getId());
                if (item.getNegatively() != 0) {// 否决项：0否1是
                    item.setNegatively(1);
                }
            }
            // 对模版中的变量进行替换
            pieceContent(bean);
            //执行保存
            contractMapper.insert(bean);
            itemMapper.batchInsert(itemList);
            // 保存 责任书档案-签订人员 信息
            savePurposeContractPersons(bean.getId(), bean.getPersonList(), user, factory);
			/*if(objectList.size() > 0){
				objectMapper.batchInsert(objectList);
			}*/
            factory.close();
            msg.setData(bean);

            return msg;
        } catch (Exception e) {
            factory.close(false);
            if (!pathList.isEmpty()) {  //删除附件
                for (String path : pathList) {
                    clientWrapper.deleteFile(path);
                }
            }
            msg.setCode(35001);
            msg.setDescription("数据库连接异常");
            return msg;
        }finally {
            factory.close();
        }
    }

    /**
     * 对模版中的变量进行替换
     *
     * @param bean
     */
    private void pieceContent(PurposeContractBean bean) {
        String spanBegin = "<span>";
        String spanEnd = "</span>";
        String pBegin = "<p>";
        String pEnd = "</p>";
        String contractContent = bean.getTemplateContent();
        String year = bean.getYear();
        contractContent = contractContent.replace("@year", spanBegin + year + spanEnd);
        // 否决指标: vetoIndicators
        // 管理指标：managementIndicators
        int countVI = 1;
        int countMI = 1;
        StringBuffer vetoIndicators = new StringBuffer();
        StringBuffer managementIndicators = new StringBuffer();
        List<PurposeItem> itemList = bean.getItemList();
        for (PurposeItem item : itemList) {// 否决项：0否1是
            if (item.getNegatively() == 0) {
                vetoIndicators.append(pBegin)
                        .append(spanBegin)
                        .append(countVI + ".")
                        .append(item.getItemName())
                        .append(item.getRule())
                        .append(item.getItemValue())
                        .append(spanEnd)
                        .append(pEnd);
                countVI++;
            } else {
                managementIndicators.append(pBegin)
                        .append(spanBegin)
                        .append(countMI + ".")
                        .append(item.getItemName())
                        .append(item.getRule())
                        .append(item.getItemValue())
                        .append(spanEnd)
                        .append(pEnd);
                countMI++;
            }
        }
        contractContent = contractContent.replace("@vetoIndicators", vetoIndicators.toString());
        contractContent = contractContent.replace("@managementIndicators", managementIndicators.toString());
        bean.setContractContent(contractContent);
    }

    @SuppressWarnings("deprecation")
    public void updateFstatusflag(String id, int fstatusflag) {
        try (SessionFactory factory = new SessionFactory();) {
            factory.getMapper(PurposeContractMapper.class).updateFstatusflag(id, fstatusflag);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
    }

    @SuppressWarnings("deprecation")
    public void updateState(String id, int state) {
        try (SessionFactory factory = new SessionFactory();) {
            factory.getMapper(PurposeContractMapper.class).updateState(id, state);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
    }

    @SuppressWarnings({"resource", "deprecation"})
    @Override
    public MessageBean<?> submit(String id, StaffBean user, String title, String note) {
        MessageBean<?> msg = MessageBean.create(0, "SUCCESS", void.class);
        if (StringUtils.isEmpty(id) || StringUtils.isEmpty(title) || StringUtils.isEmpty(note)) {
            msg.setCode(35002);
            msg.setDescription("参数校验异常");
            return msg;
        }
        SessionFactory factory = new SessionFactory();
        try {
            PurposeContractMapper contractMapper = factory.getMapper(PurposeContractMapper.class);
            PurposeContractBean bean = contractMapper.queryById(id);
            if (bean == null) {
                factory.close();
                msg.setCode(35002);
                msg.setDescription("参数校验异常");
                return msg;
            }
            if (bean.getFstatusflag() != 0) {
                factory.close();
                msg.setCode(35002);
                msg.setDescription("单据已提交");
                return msg;
            }
            //启动流程
            Audit audit = new Audit(title, note, user.getName(), new Date());
            audit.setId(DefaultIdGenerator.getInstance().generateLongId());
            audit.setTitle(title);
            audit.setDescription(note);
            audit.setInitiatorCode(user.getCode());
            audit.setTarget(PurposeContract.class.getName());
            audit.setTemplateKey(formulateTemplateKey);
            audit.setOperation(1);
            audit.setState(1);
            audit.setFlowType(1);
            audit.setFlowName(Immutable.PURPOSE_CONTRACT);
            audit.setBusinessIds(bean.getId());
            if (!flowManagement.initFlow(user, audit, new HashMap<>())) {
                msg.setCode(35005);
                msg.setDescription("流程启动失败");
                return msg;
            }
            contractMapper.updateFstatusflag(bean.getId(), 1);
            factory.close();
            return msg;
        } catch (Exception e) {
            factory.close(false);
            msg.setCode(35001);
            msg.setDescription("数据库连接异常");
            return msg;
        }finally {
            factory.close();
        }
    }


    @SuppressWarnings("deprecation")
    @Override
    public MessageBean<?> delete(String id) {
        MessageBean<?> msg = MessageBean.create(0, "success", void.class);
        try (SessionFactory factory = new SessionFactory();) {
            factory.getMapper(PurposeContractMapper.class).delete(id);
            factory.getMapper(PurposeItemMapper.class).deleteByContractId(id);
            //删除附件
            List<PurposeObject> objectList = factory.getMapper(PurposeObjectMapper.class).queryByContractId(id);
            for (PurposeObject obj : objectList) {
                clientWrapper.deleteFile(obj.getContractPath());
            }
            factory.getMapper(PurposeObjectMapper.class).deleteByContractId(id);
        } catch (Exception e) {
            msg.setCode(35001);
            msg.setDescription("数据库连接异常");
        }
        return msg;
    }

    @SuppressWarnings({"deprecation", "rawtypes"})
    @Override
    public MessageBean<?> update(PurposeContractBean bean, StaffBean user) {
        MessageBean<PurposeContractBean> msg = MessageBean.create(0, "SUCCESS", PurposeContractBean.class);
        // 检查签订人员是否为空
        if (bean.getPersonList() == null || bean.getPersonList().size() == 0) {
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription("签订人员不能为空");
            return msg;
        }
        String id = bean.getId();
        if (StringUtils.isEmpty(id)) {
            msg.setCode(35002);
            msg.setDescription("参数校验异常");
            return msg;
        }
        List<String> pathList = new ArrayList<>();
        SessionFactory factory = new SessionFactory();
        try {
            Map checkMap = addCheck(bean);
            int code = (int) checkMap.get("code");
            String description = (String) checkMap.get("description");
            if (code != 0) {
                msg.setCode(code);
                msg.setDescription(description);
                factory.close(false);
                return msg;
            }
            PurposeContractMapper contractMapper = factory.getMapper(PurposeContractMapper.class);
            PurposeContractBean temp = contractMapper.queryById(id);
            if (temp == null) {
                factory.close();
                msg.setCode(35002);
                msg.setDescription("参数校验异常");
                return msg;
            }
            if (temp.getState() != 0 && temp.getFstatusflag() != 0) {
                factory.close();
                msg.setCode(35002);
                msg.setDescription("非草稿单据不能修改");
                return msg;
            }
            String userCode = user.getCode();
            String userName = user.getName();
            Date date = new Date();
            bean.setUpdateUser(userCode);
            bean.setUpdateUserName(userName);
            bean.setUpdateTime(date);
			/*List<PurposeObject> objectList = bean.getObjectList();
			for (PurposeObject object : objectList) {
				object.setId(DefaultIdGenerator.getInstance().generateLongId());
				object.setPurposeContractId(id);
			}*/
            List<PurposeItem> itemList = bean.getItemList();
            for (PurposeItem item : itemList) {
                if (StringUtils.isEmpty(item.getItemId())) {
                    msg.setCode(BusinessCode.EXCEPTION.getCode());
                    msg.setDescription("指标信息不完整");
                    factory.close(false);
                    return msg;
                }
                if (StringUtils.isEmpty(item.getItemName())) {
                    msg.setCode(BusinessCode.EXCEPTION.getCode());
                    msg.setDescription("指标名称不能为空");
                    factory.close(false);
                    return msg;
                }
                if (StringUtils.isEmpty(item.getItemValue())) {
                    msg.setCode(BusinessCode.EXCEPTION.getCode());
                    msg.setDescription("指标值不能为空");
                    factory.close(false);
                    return msg;
                }
                if (item.getNegatively() == null) {
                    msg.setCode(BusinessCode.EXCEPTION.getCode());
                    msg.setDescription("指标否决项不能为空");
                    factory.close(false);
                    return msg;
                }
                item.setAddUser(userCode);
                item.setAddUserName(userName);
                item.setAddTime(date);
                item.setUpdateUser(userCode);
                item.setUpdateUserName(userName);
                item.setUpdateTime(date);
                item.setId(DefaultIdGenerator.getInstance().generateLongId());
                item.setPurposeContractId(id);
                // 否决项：0否1是
                if (item.getNegatively() != 0) {
                    item.setNegatively(1);
                }
            }
            PurposeItemMapper itemMapper = factory.getMapper(PurposeItemMapper.class);
//			PurposeObjectMapper objectMapper = factory.getMapper(PurposeObjectMapper.class);
            //先删除原来的子表数据
            itemMapper.deleteByContractId(id);
//			objectMapper.deleteByContractId(id);

            // 对模版中的变量进行替换
            pieceContent(bean);
            //执行保存
            contractMapper.update(bean);
            itemMapper.batchInsert(itemList);
            // 根据 责任书档案id 删除签订人员信息
            factory.getMapper(PurposeContractMapper.class).deletePersonsByPurposeContractId(bean.getId());
            // 保存 责任书档案-签订人员 信息
            savePurposeContractPersons(bean.getId(), bean.getPersonList(), user, factory);
			/*if(objectList.size() > 0){
				objectMapper.batchInsert(objectList);
			}*/
            factory.close();
            msg.setData(bean);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            factory.close(false);
            if (!pathList.isEmpty()) {  //删除附件
                for (String path : pathList) {
                    clientWrapper.deleteFile(path);
                }
            }
            msg.setCode(35001);
            msg.setDescription("数据库连接异常");
            return msg;
        }finally {
            factory.close();
        }
    }

    @SuppressWarnings({"unchecked", "rawtypes", "deprecation"})
    @Override
    public MessageBean<?> sign(StaffBean user, String id, String partyA, String partyB, String staffMsgs) {
        MessageBean<?> msg = MessageBean.create(0, "SUCCESS", void.class);
        if (StringUtils.isEmpty(id) || StringUtils.isEmpty(partyA) || StringUtils.isEmpty(partyB)
                || staffMsgs.isEmpty()) {
            msg.setCode(35002);
            msg.setDescription("参数校验异常");
            return msg;
        }
        MessageBean<?> temp = queryById(id);
        if (temp.getCode() != 0) {
            return temp;
        }
        if (temp.getData() == null) {
            msg.setCode(35002);
            msg.setDescription("参数校验异常");
            return msg;
        }
        PurposeContractBean bean = (PurposeContractBean) temp.getData();
        if (bean.getFstatusflag() != 2) {
            msg.setCode(35002);
            msg.setDescription("责任书制定审批流程未完成");
            return msg;
        }
        List<PurposeItem> itemList = bean.getItemList();
        bean.setBillType(BILLTYPE_2); //责任书类型：1制定，2档案
        bean.setObjectId(partyA);
        bean.setObjectName(partyB);
        Date date = new Date();
        bean.setAddUser(user.getCode());
        bean.setAddUserName(user.getName());
        bean.setAddTime(date);
        bean.setUpdateUser(user.getCode());
        bean.setUpdateUserName(user.getName());
        bean.setUpdateTime(null);
        List<Map> staffs = JSON.parseArray(staffMsgs, Map.class);
        // String[] staffCodeArray = staffMsgs.split(",");
        try (SessionFactory factory = new SessionFactory();) {
            for (Map staff : staffs) {
                bean.setState(STATE_0);
                bean.setStaffLiable(staff.get("staffCode").toString());//责任人
                bean.setStaffName(staff.get("staffName").toString());//责任人
                bean.setId(DefaultIdGenerator.getInstance().generateLongId());

                for (PurposeItem item : itemList) {
                    item.setId(null);
                    item.setId(DefaultIdGenerator.getInstance().generateLongId());
                    item.setPurposeContractId(bean.getId());
                }
                PurposeContractMapper contractMapper = factory.getMapper(PurposeContractMapper.class);
                PurposeItemMapper itemMapper = factory.getMapper(PurposeItemMapper.class);
                //启动流程
                String title = "安全责任书签订";
                Audit audit = new Audit(title, title, bean.getAddUserName(), new Date());
                audit.setId(DefaultIdGenerator.getInstance().generateLongId());
                audit.setTitle(title);
                audit.setDescription(title);
                audit.setInitiatorCode(bean.getAddUser());
                audit.setTarget(PurposeContract.class.getName());
                audit.setTemplateKey(signTemplateKey);
                audit.setOperation(1);
                audit.setState(1);
                audit.setFlowType(1);
                audit.setFlowName(Immutable.PURPOSE_CONTRACT_SIGNED);
                audit.setBusinessIds(bean.getId());
                Map map = new HashMap<>();
                map.put("approver", bean.getStaffLiable());

                StaffBean addUser = new StaffBean();
                addUser.setCode(bean.getAddUser());
                addUser.setName(bean.getAddUserName());
                if (flowManagement.initFlow(addUser, audit, map)) { //启动流程
                    bean.setFstatusflag(FSTATUSFLAG_1);
                    contractMapper.insert(bean); //保存责任书
                    itemMapper.batchInsert(itemList);//保存指标
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }
        return msg;
    }

    @Override
    public MessageBean<?> signList(StaffBean user, ContractQueryBean queryBean) {
        MessageBean<DataBean> msg = MessageBean.create(0, "SUCCESS", DataBean.class);
        if (user == null) {
            msg.setCode(BusinessCode.NOT_LOGIN.getCode());
            msg.setDescription(BusinessCode.NOT_LOGIN.getDescription());
            return msg;
        }
        Integer totalPage = null;
        Integer totalNumber = null;
        Integer start = null;
        Integer end = null;
        Integer page = queryBean.getPage();
        Integer pageSize = queryBean.getPageSize();
        if (null != page && pageSize != null) {
            if (page > 0 && pageSize > 0) {
            } else {
                //第一页 10条数据
                page = 1;
                pageSize = 10;
            }
            start = (page <= 1) ? 0 : (page - 1) * pageSize;
            end = pageSize;
        }
        queryBean.setStart(start);
        queryBean.setEnd(end);
        String name = queryBean.getName();
        if (name != null) {
            name = "%" + name + "%";
        }
        queryBean.setName(name);
        try (SessionFactory factory = new SessionFactory();) {
            totalNumber = factory.getMapper(PurposeContractMapper.class).signCount(user.getCode(), queryBean);
            if (totalNumber == null) {
                totalNumber = 0;
            }
            if (start != null && end != null) {
                totalPage = (totalNumber + pageSize - 1) / pageSize;
            } else {
                totalPage = 1;
                page = totalPage;
                pageSize = totalNumber;
            }
            DataBean data = new DataBean();
            data.setList(factory.getMapper(PurposeContractMapper.class).signQuery(user.getCode(), queryBean));
            data.setPageNo(page);
            data.setPageSize(pageSize);
            data.setTotalNumber(totalNumber);
            data.setTotalPage(totalPage);
            msg.setData(data);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(35001);
            msg.setDescription("数据库连接异常");
            return msg;
        }
        return msg;
    }

    @Override
    public MessageBean batchSubmit(StaffBean user, String purposeContractIds, Integer purposeContractType, String personCode) {
        MessageBean msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), void.class);
        if (StringUtils.isEmpty(purposeContractIds)) {
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription("请选择要签订的责任书档案");
            return msg;
        }
        if (StringUtils.isEmpty(personCode)) {
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription("审核人信息不能为空");
            return msg;
        }
        SessionFactory factory = new SessionFactory();
        try {
            PurposeContractMapper mapper = factory.getMapper(PurposeContractMapper.class);
            Audit audit = new Audit("责任书档案", "责任书制定审批", user.getName(), new Date());
            audit.setTitle("责任书档案");
            audit.setDescription("责任书制定审批");

            audit.setId(DefaultIdGenerator.getInstance().generateLongId());
            audit.setInitiatorCode(user.getCode());
            audit.setTarget(this.getClass().getName());
            // 责任书制定流程 1-集团、2-片区、3-公司、4-部门、5-厂站、6-班组
            if (purposeContractType == 1) {
                audit.setTemplateKey(templateKeyJT);
            } else if (purposeContractType == 2) {
                audit.setTemplateKey(templateKeyPQ);
            } else if (purposeContractType == 3) {
                audit.setTemplateKey(templateKeyGS);
            } else if (purposeContractType == 4) {
                audit.setTemplateKey(templateKeyBM);
            } else if (purposeContractType == 5) {
                audit.setTemplateKey(templateKeyCZ);
            } else if (purposeContractType == 6) {
                audit.setTemplateKey(templateKeyBZ);
            } else {
                factory.close(false);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("下发类型错误");
                return msg;
            }
            List<String> idList = Splitter.on(",").omitEmptyStrings().trimResults().splitToList(purposeContractIds);
            // 修改 责任书档案 的签订类型 (1-集团、2-片区、3-公司、4-部门、5-厂站、6-班组)
            for (String id : idList) {// 只能修改 流程状态：0草稿 1审批中 2审批通过 为草稿的数据
                if (mapper.updateFstatusflagById(id, purposeContractType, FSTATUSFLAG_1) != 1) {
                    factory.close(false);
                    msg.setCode(BusinessCode.EXCEPTION.getCode());
                    msg.setDescription("存在已经下发过的责任书档案");
                    return msg;
                }
            }
            audit.setOperation(1);
            audit.setState(1);
            audit.setFlowType(1);
            audit.setFlowName("责任书制定审批");
            audit.setBusinessIds(new Gson().toJson(idList));
            Map map = new HashMap();
            map.put("personCode", personCode);
            audit.setOtherBusinessIds("flag:formulate");
            if (!flowManagement.initFlow(user, audit, map)) {
                factory.close(false);
                msg.setCode(com.koron.hazardsource.util.BusinessCode.MESSAGE_CODE_FLOW_EXCEPTION);
                msg.setDescription(com.koron.hazardsource.util.BusinessCode.MESSAGE_DESCRIPTION_FLOW_EXCEPTION);
                return msg;
            }
            factory.close();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            factory.close(false);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }finally {
            factory.close();
        }
        return msg;
    }


    @SuppressWarnings("deprecation")
    @Override
    public MessageBean<?> signed(String id, MultipartFile file, StaffBean user) {
        MessageBean<?> msg = MessageBean.create(0, "SUCCESS", void.class);
        if (StringUtils.isEmpty(id) || file == null || user == null) {
            msg.setCode(35002);
            msg.setDescription("参数校验异常");
            return msg;
        }
        msg = queryById(id);
        if (msg.getData() == null) {
            msg.setCode(35002);
            msg.setDescription("参数校验异常");
            return msg;
        }
        PurposeContractBean bean = (PurposeContractBean) msg.getData();
        if (1 == bean.getState()) {
            msg.setCode(35002);
            msg.setDescription("已签订");
            return msg;
        }
        String staffCode = bean.getStaffLiable();
        if (!user.getCode().equals(staffCode)) {
            msg.setCode(35002);
            msg.setDescription("无签订权限");
            return msg;
        }
        String filePath = "";
        SessionFactory factory = new SessionFactory();
        try {
            PurposeContractMapper contractMapper = factory.getMapper(PurposeContractMapper.class);
            bean.setUpdateUser(user.getCode());
            bean.setUpdateUserName(user.getName());
            bean.setUpdateTime(new Date());
            bean.setState(STATE_1);//设置为已签订

            List<PurposeObject> objectList = bean.getObjectList();
            //上传附件
            String fileName = file.getOriginalFilename();
            filePath = clientWrapper.uploadFile(file);//文件上传的路径

            for (PurposeObject objcet : objectList) {
                objcet.setId(DefaultIdGenerator.getInstance().generateLongId());
                objcet.setPurposeContractId(bean.getId());
                objcet.setUpdateTime(new Date());
                objcet.setUpdateUser(user.getCode());
                objcet.setUpdateUserName(user.getName());
                objcet.setContractName(fileName);
                objcet.setContractPath(filePath);
            }

            PurposeObjectMapper objectMapper = factory.getMapper(PurposeObjectMapper.class);
            //先删除原来的子表数据
            objectMapper.deleteByContractId(bean.getId());
            //执行保存
            contractMapper.signed(bean);
            objectMapper.batchInsert(objectList);
            factory.close();
            return msg;
        } catch (Exception e) {
            factory.close(false);
            if (!StringUtils.isEmpty(filePath)) {  //删除附件
                clientWrapper.deleteFile(filePath);
            }
            msg.setCode(35001);
            msg.setDescription("数据库连接异常");
            return msg;
        }finally {
            factory.close();
        }
    }

    @SuppressWarnings("deprecation")
    @Override
    public MessageBean<PurposeContractBean> queryById(String id) {
        MessageBean<PurposeContractBean> msg = MessageBean.create(0, "SUCCESS", PurposeContractBean.class);
        if (StringUtils.isEmpty(id)) {
            msg.setCode(35002);
            msg.setDescription("参数校验异常");
            return msg;
        }
        try (SessionFactory factory = new SessionFactory();) {
            PurposeContractMapper contractMapper = factory.getMapper(PurposeContractMapper.class);
            PurposeItemMapper itemMapper = factory.getMapper(PurposeItemMapper.class);
            PurposeObjectMapper objectMapper = factory.getMapper(PurposeObjectMapper.class);
            List<PurposeContractPersons> persons = contractMapper.queryPersonsByPurposeContractId(id);
            PurposeContractBean bean = contractMapper.queryById(id);
            if (bean == null) {
                return msg;
            }
            bean.setItemList(itemMapper.queryByContractId(id));
            bean.setObjectList(objectMapper.queryByContractId(id));
            bean.setPersonList(Optional.ofNullable(persons).orElse(new ArrayList<>(0)));
            msg.setData(bean);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(35001);
            msg.setDescription("数据库连接异常");
            return msg;
        }
    }

    @SuppressWarnings({"unchecked", "deprecation", "rawtypes"})
    @Override
    public MessageBean<?> list(ContractQueryBean queryBean) {
        MessageBean<DataBean> msg = MessageBean.create(0, "SUCCESS", DataBean.class);
        Integer totalPage = null;
        Integer totalNumber = null;
        Integer start = null;
        Integer end = null;
        Integer page = queryBean.getPage();
        Integer pageSize = queryBean.getPageSize();
        if (null != page && pageSize != null) {
            if (page > 0 && pageSize > 0) {
            } else {
                //第一页 10条数据
                page = 1;
                pageSize = 10;
            }
            start = (page <= 1) ? 0 : (page - 1) * pageSize;
            end = pageSize;
        }
        queryBean.setStart(start);
        queryBean.setEnd(end);
        String name = queryBean.getName();
        if (name != null) {
            name = "%" + name + "%";
        }
        queryBean.setName(name);
        try (SessionFactory factory = new SessionFactory();) {
            totalNumber = factory.getMapper(PurposeContractMapper.class).count(queryBean);
            if (totalNumber == null) {
                totalNumber = 0;
            }
            if (start != null && end != null) {
                totalPage = (totalNumber + pageSize - 1) / pageSize;
            } else {
                totalPage = 1;
                page = totalPage;
                pageSize = totalNumber;
            }
            DataBean data = new DataBean();
            data.setList(queryList(queryBean));
            data.setPageNo(page);
            data.setPageSize(pageSize);
            data.setTotalNumber(totalNumber);
            data.setTotalPage(totalPage);
            msg.setData(data);
        } catch (Exception e) {
            msg.setCode(35001);
            msg.setDescription("数据库连接异常");
            return msg;
        }
        return msg;
    }

    @SuppressWarnings({"unchecked", "rawtypes"})
    private Map addCheck(PurposeContractBean bean) {
        Map map = new HashMap();
        List<PurposeItem> itemList = bean.getItemList();
        if (itemList == null) {
            map.put("code", 35002);
            map.put("description", "未填写考核指标信息");
            return map;
        }
        if (StringUtils.isEmpty(bean.getName())) {
            map.put("code", 35002);
            map.put("description", "名称不能为空");
            return map;
        }
        if (StringUtils.isEmpty(bean.getYear())) {
            map.put("code", 35002);
            map.put("description", "年度不能为空");
            return map;
        }
		/*if(bean.getObjectType() == null){
			map.put("code", 35002);
    		map.put("description", "类型不能为空");
    		return map;
		}
		if(StringUtils.isEmpty(bean.getObjectId())){
			map.put("code", 35002);
    		map.put("description", "责任人不能为空");
    		return map;
		}*/
        int itemRow = 1;
        for (PurposeItem item : itemList) {
            String row = "行" + itemRow;
            if (StringUtils.isEmpty(item.getItemId())) {
                map.put("code", 35002);
                map.put("description", row + "考核指标不能为空");
                return map;
            }
            if (StringUtils.isEmpty(item.getItemName())) {
                map.put("code", 35002);
                map.put("description", row + "指标名称不能为空");
                return map;
            }
			/*if(StringUtils.isEmpty(item.getRule())){
				map.put("code", 35002);
	    		map.put("description", row+"指标规则不能为空");
	    		return map;
			}*/
            itemRow++;
        }
        map.put("code", 0);
        map.put("description", "校验成功");
        return map;
    }

    @SuppressWarnings("deprecation")
    public List<PurposeContractBean> queryList(ContractQueryBean queryBean) {
        List<PurposeContractBean> list = new ArrayList<>();
        try (SessionFactory factory = new SessionFactory();) {
            PurposeContractMapper contractMapper = factory.getMapper(PurposeContractMapper.class);
            list = contractMapper.query(queryBean);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        return list;
    }

    /**
     * 保存 责任书档案-签订人员 信息
     *
     * @param purposeContractId 责任书档案id
     * @param persons           签订人员list
     * @param user
     * @param factory
     */
    private void savePurposeContractPersons(String purposeContractId, List<PurposeContractPersons> persons,
                                            StaffBean user, SessionFactory factory) throws Exception {
        try {
            Date date = new Date();
            for (PurposeContractPersons person : persons) {
                person.setId(DefaultIdGenerator.getInstance().generateLongId());
                person.setPurposeContractId(purposeContractId);
                person.setAddTime(date);
                person.setAddUser(user.getCode());
                person.setAddUserName(user.getName());
                person.setUpdateTime(date);
                person.setUpdateUser(user.getCode());
                person.setUpdateUserName(user.getName());
            }
            factory.getMapper(PurposeContractMapper.class).batchInsertPCPersons(persons);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            throw new Exception("新增责任书档案-签订人员失败" + e.getMessage());
        }
    }

    @Override
    public void editApproval(Audit audit) {
        Optional.ofNullable(audit)
                .map(obj -> obj.getBusinessIds())
                .map(ids -> {
                    List<String> list = JSON.parseArray(ids, String.class);
                    return Optional.ofNullable(list);
                }).map(idsList -> {
            List<String> idList = idsList.get();
            Optional.ofNullable(idList).map(ids -> {
                SessionFactory factory = new SessionFactory();
                try {
                    String flag = audit.getOtherBusinessIds();
                    if ("flag:formulate".equals(flag)) {// 责任书制定流程结束执行代码
                        StaffBean user = new StaffBean();
                        WorkflowService flowService = audit.getCtx().getBean(WorkflowServiceImpl.class);
                        String result = flowService.grabHistory(audit.getFlowInstanceId());
                        JSONObject jsonObject = JSONObject.parseObject(result);
                        if (jsonObject.getInteger("code") == 0) {
                            JSONArray array = jsonObject.getJSONArray("data");
                            for (int i = 0; i < array.size(); i++) {
                                JSONObject jo = array.getJSONObject(i);
                                if (StringUtils.isEmpty(jo.getString("nexttaskId"))) {
                                    user.setCode(jo.getString("nowAssignee"));
                                    Util util = audit.getCtx().getBean(Util.class);
                                    MessageBean<List<StaffBean>> list = (MessageBean<List<StaffBean>>) util.staff(user.getCode(), 3);
                                    if (list.getCode() == 0) {
                                        user = list.getData().get(0);
                                    }
                                    break;
                                }
                            }
                        }
                        if (user == null) {
                            throw new Exception("没有获取到流程最后一个审批人节点信息");
                        }
                        for (String id : idList) {
                            // 修改 流程状态
                            factory.getMapper(PurposeContractMapper.class).updateFstatusflag(id, FSTATUSFLAG_2);
                            // 将责任书制定 copy 一份改为责任书档案
                            MessageBean<PurposeContractBean> temp = queryById(id);
                            PurposeContractBean bean = temp.getData();
                            List<PurposeItem> itemList = bean.getItemList();
                            bean.setBillType(BILLTYPE_2); //责任书类型：1制定，2档案
                            // 甲方:最后一个审批人
                            bean.setObjectId(user.getName());
                            Date date = new Date();
                            bean.setAddUser(user.getCode());
                            bean.setAddUserName(user.getName());
                            bean.setAddTime(date);
                            bean.setUpdateUser(user.getCode());
                            bean.setUpdateUserName(user.getName());
                            bean.setUpdateTime(date);
                            // 签订人员
                            List<PurposeContractPersons> personList = bean.getPersonList();
                            // String[] staffCodeArray = staffMsgs.split(",");
                            for (PurposeContractPersons person : personList) {
                                bean.setState(STATE_0);
                                bean.setStaffLiable(person.getPersonCode());//责任人
                                bean.setStaffName(person.getPersonName());//责任人
                                bean.setId(DefaultIdGenerator.getInstance().generateLongId());
                                // 乙方:签订人
                                bean.setObjectName(person.getPersonName());

                                for (PurposeItem item : itemList) {
                                    item.setId(null);
                                    item.setId(DefaultIdGenerator.getInstance().generateLongId());
                                    item.setPurposeContractId(bean.getId());
                                }
                                PurposeContractMapper contractMapper = factory.getMapper(PurposeContractMapper.class);
                                PurposeItemMapper itemMapper = factory.getMapper(PurposeItemMapper.class);
                                // 启动流程
                                String title = "安全责任书签订";
                                Audit newAudit = new Audit(title, title + "(" + bean.getObjectId() + "-" + bean.getObjectName() + ")", bean.getAddUserName(), new Date());
                                newAudit.setId(DefaultIdGenerator.getInstance().generateLongId());
                                newAudit.setTitle(title);
                                newAudit.setInitiatorCode(bean.getAddUser());
                                newAudit.setTarget(this.getClass().getName());
                                newAudit.setTemplateKey("purpose_contract_sign");
                                newAudit.setOperation(1);
                                newAudit.setState(1);
                                newAudit.setFlowType(1);
                                newAudit.setFlowName(Immutable.PURPOSE_CONTRACT_SIGNED);
                                newAudit.setBusinessIds(new Gson().toJson(Arrays.asList(bean.getId())));
                                newAudit.setOtherBusinessIds("flag:record");
                                Map map = new HashMap<>();
                                map.put("approver", bean.getStaffLiable());
                                StaffBean addUser = new StaffBean();
                                addUser.setCode(bean.getAddUser());
                                addUser.setName(bean.getAddUserName());
                                FlowManagement flowManagement = audit.getCtx().getBean(FlowManagement.class);
                                if (flowManagement.initFlow(addUser, newAudit, map)) { //启动流程
                                    contractMapper.insert(bean); //保存责任书
                                    itemMapper.batchInsert(itemList);//保存指标
                                } else {
                                    factory.close(false);
                                }
                            }
                        }
                    } else if ("flag:record".equals(flag)) {// 责任书档案流程结束执行代码
                        for (String id : idList) {
                            factory.getMapper(PurposeContractMapper.class).updateState(id, STATE_1);
                        }
                    }
                    factory.close();
                } catch (Exception e) {
                    logger.error(e.getMessage(),e);
                    factory.close(false);
                }
                return null;
            });
            return null;
        });
    }


    @Override
    public void processDiscard(Audit audit) {
        // TODO Auto-generated method stub

    }

    @Override
    public void discardApproval(Audit audit) {
        Optional.ofNullable(audit)
                .map(obj -> obj.getBusinessIds())
                .map(ids -> {
                    List<String> list = JSON.parseArray(ids, String.class);
                    return Optional.ofNullable(list);
                }).map(idsList -> {
            List<String> idList = idsList.get();
            Optional.ofNullable(idList).map(ids -> {
                SessionFactory factory = new SessionFactory();
                try {
                    String flag = audit.getOtherBusinessIds();
                    if ("flag:formulate".equals(flag)) {// 责任书制定流程废弃执行代码
                        for (String id : idList) {
                            factory.getMapper(PurposeContractMapper.class).updateFstatusflag(id, FSTATUSFLAG_0);
                        }
                    } else if ("flag:record".equals(flag)) {// 责任书档案流程废弃执行代码
                        for (String id : idList) {
                            factory.getMapper(PurposeContractMapper.class).updateState(id, STATE_2);
                        }
                    }
                    factory.close();
                } catch (Exception e) {
                    logger.error(e.getMessage(),e);
                    factory.close(false);
                }
                return null;
            });
            return null;
        });
    }

    @Override
    public void reject(Audit audit, List<String> userIdList) {
        // TODO 流程驳回操作
    }

    @Override
    public void passApproval(Integer operation, Audit audit) {
        // TODO 流程提交成功操作
    }
}
